import { t } from 'i18next'
import { useEffect, useMemo, useRef } from 'react'
import shallow from 'zustand/shallow'
import { terminalEntity, ListTranslator } from './translator'
import { differenceBy, findIndex } from 'lodash-es'
import { Alert, confirmModal } from '@/components/Alert'
import { InnerInputRef, Message, Modal } from '@kedacom/react-next'
import { useMixStore } from './store'
import {
	fetchAddMixPlan,
	fetchDeleteMixPlan,
	fetchGetMixInfo,
	fetchGetMixPlanDetail,
	fetchGetMixPlanList,
	fetchStart,
	fetchStopMix,
	fetchUpdateMixPlan,
} from '@/api/manager/mix'
import { PlanResponsePollEntity } from '@/api/manager/mix/interface'
import { useMccStore } from '../../store'
import { MtEntity } from '@/api/manager/mt'
import { DropData } from '@/api/manager/type'
import useLock from '@/hooks/useLock'
import { useParamsStore } from '../main/store'
import { actionButtonsCancel } from '../../store.actionButton'

export const useData = () => {
	const meetingMoid = useMccStore((state) => state.mccInfo.meetingMoid)
	const {
		list,
		update,
		state,
		planOptions,
		preName,
		planValue,
		getPara,
		mode,
		name,
		change_plan,
		getPlanPara,
		custom_mix_list,
		is_call_back,
		is_call_back_mt,
		getMixMute,
		render,
		changeMix,
		renderPreMix,
	} = useMixStore(
		(state) => ({
			list: state.list,
			state: state.state,
			planOptions: state.planOptions,
			preName: state.preName,
			planValue: state.planValue,
			members: state.members,
			membersDataBackup: state.membersDataBackup,
			isEdit: state.isEdit,
			mode: state.mode,
			name: state.name,
			update: state.update,
			getPara: state.getPara,
			getPlanPara: state.getPlanPara,
			resetMix: state.resetMix,
			change_plan: state.change_plan,
			custom_mix_list: state.custom_mix_list,
			getMixMute: state.getMixMute,
			is_call_back: state.is_call_back,
			is_call_back_mt: state.is_call_back_mt,
			render: state.render,
			changeMix: state.changeMix,
			renderPreMix: state.renderPreMix,
		}),
		shallow
	)
	const inputRef = useRef<InnerInputRef>(null)
	/**轮询状态下禁止操作*/
	const disabled = useMemo(() => {
		if (state === 1) {
			if (change_plan) {
				return false
			} else {
				return true
			}
		}
		return false
	}, [state])
	/**根据全局的设置的预案名称/电视墙预案列表获取选中的值*/
	useEffect(() => {
		var value = planOptions.find((item) => item.label === preName)?.value ?? '0'
		update({ planValue: value })
	}, [preName, planOptions])
	/**初始化加载数据*/
	useEffect(() => {
		getMixInfo()
	}, [])
	useEffect(() => {})
	/**请求混音数据*/
	const getMixInfo = async () => {
		let res = await fetchGetMixInfo(meetingMoid)
		if (res.success) {
			/**开启state为1 返回有数据   state 为0 接口无数据返回 */
			let _data = res.data
			if (res.data) {
				let _state = res.data ? 1 : 0
				_data = Object.assign(res.data, { state: _state })
			}
			renderPreMix(_data)
			loadPlanData()
			is_call_back && render(is_call_back_mt)
		} else {
			Alert("t('获取混音信息失败')")
		}
		update({
			is_call_back: false,
			is_call_back_mt: [],
		})
	}
	/**加载预案 */
	const loadPlanData = async (planName?: string) => {
		const res = await fetchGetMixPlanList(meetingMoid)
		if (res.success && res.data) {
			const planData = res.data
			let arr = planData ? planData.map((item) => ({ label: item.name, value: item.id })) : []
			arr.unshift({ label: t('不使用预案'), value: '0' })
			update({ planOptions: arr })
			/**新增预案,更新预案(刷新预案列表)*/
			planName && update({ preName: planName })
		} else {
			Alert(t('获取混音预案失败'))
		}
	}
	/**开始混音 */
	const startMix = async () => {
		//定制混音
		/**语音激励 */
		const isInspire = useMccStore.getState().mccInfo.voiceInspireState
		if (mode === 2) {
			if (isInspire) {
				Alert(t('您无法同时开启定制混音功能和语音激励功能'))
				return false
			}
			if (custom_mix_list.length === 0) {
				Alert(t('定制混音时混音列表不能为空'))
				return false
			}
		}
		const params = getPara()
		const res = await fetchStart(meetingMoid, params)
		!res.success && Alert(res.description || t('设置混音失败'))
	}
	/**结束混音 */
	const stopMix = async () => {
		const success = await fetchStopMix(meetingMoid, 1, mode)
		!success && Alert(t('结束混音失败'))
		success && update({ mute: 0 })
	}
	/**渲染混音数据 */
	//拖拽
	const handleDrop = (dataTransfer: DropData, index: number) => {
		if (dataTransfer && dataTransfer.data && dataTransfer.data.mt) {
			/**智能混音不能拖拽终端 */
			if (mode === 1) return
			let mt = dataTransfer.data.mt
			let from = dataTransfer.from
			if (!mt.isMt && from !== 'mix') {
				//只有终端能够加入混音列表
				Alert(t('会议不能加入定制混音'))
				return false
			}
			if (mt.online === 0 && from !== 'mix') {
				Alert(t('离线终端不能加入定制混音'))
				return false
			}
			dealDrop({
				mts: ListTranslator([mt as MtEntity]),
				from: dataTransfer.from,
				dropIndex: index,
			})
		}
	}
	//拖拽进入列表
	const dealDrop = ({ mts, from, dropIndex }: terminalEntity) => {
		if (from !== 'mix') {
			const insertList = differenceBy(mts, custom_mix_list, (x) => x.mtKey)
			if (insertList.length === 0) return //重复添加
			let newList = [...custom_mix_list.slice(0, dropIndex), ...insertList, ...custom_mix_list.slice(dropIndex)]
			update({ custom_mix_list: newList })
			changeMix()
		} else {
			const baseList = differenceBy(custom_mix_list, mts, (x) => x.mtKey)
			let insertToBaseIndex = dropIndex
			const baseListMtKeys = baseList.map((l) => l.mtKey)
			const nextFirstBaseListIndex = findIndex(
				custom_mix_list,
				(l) => baseListMtKeys.includes(l.mtKey),
				dropIndex
			)
			if (nextFirstBaseListIndex === -1) {
				insertToBaseIndex = baseList.length
			} else {
				insertToBaseIndex = baseList.findIndex((l) => l.mtKey === custom_mix_list[nextFirstBaseListIndex].mtKey)
			}
			update({
				custom_mix_list: [
					...baseList.slice(0, insertToBaseIndex),
					...mts,
					...baseList.slice(insertToBaseIndex),
				],
			})
		}
	}
	/**点击终端选项删除*/
	const handleRemoveMt = (mtKey: string) => {
		const unRemove = list.filter((l) => l.mtKey !== mtKey)
		update({ list: unRemove })
	}
	/**清空终端*/
	const clear = () => {
		update({
			_start: '',
			list: [],
		})
	}
	/**返回操作*/
	const handleReturnBack = () => {
		useMccStore.getState().setCurPage('mcc_main')
		actionButtonsCancel()
	}
	/**点击保存预案(清空输入框名称/打开模态框)*/
	const savePlan = async () => {
		planValue === '0' ? update({ name: '', isSavePlanOpen: true }) : updatePlan()
	}
	/**更新预案*/
	const updatePlan = useLock(async () => {
		const params = getPlanPara(true)
		const res = await fetchUpdateMixPlan(meetingMoid, planValue, params)
		res.success ? Message.info(t('预案保存成功')) : Alert(res.description || t('预案保存失败'))
		res.success && loadPlanData(preName)
	})
	/**新增预案*/
	const addPlan = useLock(async () => {
		const params = getPlanPara(false)
		let valid = await inputRef.current?.valid()
		if (!valid) return
		const res = await fetchAddMixPlan(meetingMoid, params)
		if (res.success) {
			loadPlanData(name)
			Message.info(t('预案保存成功'))
			update({ isSavePlanOpen: false })
		} else {
			Alert(res.description || t('预案保存失败'))
		}
	})
	/**切换预案*/
	const changePlan = async (value: string) => {
		if (change_plan === 1) return
		const item = planOptions.find((item) => item.value === value)
		update({ planValue: value, preName: item?.label, custom_mix_list: [], intelligent_mix_list: [] })
		if (value !== '0') {
			update({ change_plan: 1 })
			const res = await fetchGetMixPlanDetail(meetingMoid, value)
			if (res.success) {
				Message.info(t('预案载入成功'))
				planHandle(res)
			} else {
				update({ change_plan: 0 })
				Alert(t('获取混音预案失败'))
			}
		} else {
			/**切换到不使用预案 */
			update({
				custom_mix_list: [],
				intelligent_mix_list: [],
				state: 0,
				mode: 1,
			})
		}
	}
	const planHandle = (_data: PlanResponsePollEntity) => {
		const { mode, members, name } = _data
		if (mode === 1) {
			useParamsStore.getState().hideActionButton()
			update({
				state: 0,
				mode: 1,
				radioFlag: false,
				change_plan: 0,
				mute: 0,
				preName: name,
			})
		} else if (mode === 2) {
			useParamsStore.getState().showActionButton()
			/**true 代表全部哑音  false代表部分哑音 */
			const _all_mute = getMixMute(members)
			update({
				radioFlag: false,
				state: 0,
				mode: 2,
				preName: name,
				mute: Number(!_all_mute),
				change_plan: 0,
				custom_mix_list: ListTranslator(members || []),
			})
		}
	}
	/**删除预案 */
	const deletePlan = async (item: { label: string; value: string }) => {
		/**判断删除的预案是否是当前选中的*/
		let isCur = planValue === item.value ? true : false
		let _plan_option = planOptions.filter((v) => item.value !== v.value)
		confirmModal({
			msg: t('是否确定删除{{name}}', { name: item.label }),
			onOk: async () => {
				const res = await fetchDeleteMixPlan(meetingMoid, item.value)
				if (res.success) {
					isCur && update({ preName: t('不使用预案'), planOptions: _plan_option })
					!isCur && update({ planOptions: _plan_option })
				} else {
					Alert(res.description || t('删除失败'))
				}
			},
		})
	}
	return {
		inputRef,
		/**加载预案数据 */
		loadPlanData,
		/**切换预案 */
		changePlan,
		/**删除预案 */
		deletePlan,
		handleDrop,
		clear,
		/**开始混音 */
		startMix,
		/**结束混音 */
		stopMix,
		/**返回操作设置主页 */
		handleReturnBack,
		/**保存预案 */
		savePlan,
		/**手动删除终端 */
		handleRemoveMt,
		/**新增预案 */
		addPlan,
		disabled,
	}
}
